import supabase from '@/lib/supabase'
import cuid from 'cuid'

export default async function post(req, res) {
  switch (req.method) {
    case 'GET': {
      const { postId, siteId, published } = req.query

      if (postId) {
        // get individual post
        const {
          data: [post],
        } = await supabase.from('post').select('*').eq('id', postId)

        const { data } = await supabase
          .from('site')
          .select('*')
          .eq('id', post.siteId)

        res.status(200).json({ ...post, site: data[0] })
      } else {
        // get all posts
        const { data: posts } = await supabase
          .from('post')
          .select('*')
          .eq('siteId', siteId)

        const { data: siteData } = await supabase
          .from('site')
          .select('*')
          .eq('id', siteId)

        res.status(200).json({ posts, site: siteData[0] })
      }
      return
    }
    case 'POST': {
      // create post
      const { siteId } = req.query
      const { data } = await supabase.from('post').upsert({
        image: `/placeholder.png`,
        imageBlurhash:
          '',
        siteId,
        slug: cuid(),
        content: [
          {
            type: 'paragraph',
            children: [{ text: `Write about your post` }],
          },
        ],
      })

      res.status(200).json({ postId: data[0].id })
      return
    }
    case 'DELETE': {
      // delete post
      const { postId } = req.query
      await supabase.from('post').delete().match({ id: postId })

      res.status(200).end()
      return
    }
    case 'PUT': {
      // publish post, update post content, update post settings
      const {
        id,
        title,
        description,
        content,
        slug,
        image,
        imageBlurhash,
        published,
      } = req.body

      const { data } = await supabase.from('post').upsert({
        title,
        description,
        content,
        slug,
        image,
        imageBlurhash,
        published,
        id,
      })

      res.status(200).json(data[0])
    }
    default:
      res.status(405).end()
      return
  }
}
